//
//  TZWStatusModel.swift
//  Sinaweibotzw
//
//  Created by 檀志文 on 16/4/13.
//  Copyright © 2016年 ios檀志文. All rights reserved.
//

import UIKit
import SDWebImage

class TZWStatusModel: NSObject {
//    单例
    static let sharedInstance: TZWStatusModel = TZWStatusModel()
    
//    加载本地的数据
    private func loadLocalStatuses() {
        let  path = NSBundle.mainBundle().pathForResource("statuses", ofType: "json")!
        let data = NSData(contentsOfFile: path)!
        do{
            let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String: AnyObject]
            HMPrint("json: \(json)")
            
        }catch let error as NSError{
            HMPrint("json序列化异常: \(error)")
        }
    }
    
    
    /// 加载微博数据
    /// since_id: 下拉刷新获取最新微薄
    /// max_id: 上拉加载老的数据
    func loadStatus(since_id: Int64, max_id: Int64, loadStatusCallback: (statuses: [TZWStatus]?, error: NSError?) ->()){
        
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
//        2 参数
        var parameters: [String: AnyObject] = ["access_token": TZWUserAccoutViewModel.sharedInstance.userAccount!.access_token!]
        // 将since_id, max_id拼接到请求参数里面
        if since_id > 0 {   // 别人转了since_id
            parameters["since_id"] = NSNumber(longLong: since_id)
        } else if max_id > 0 {
            parameters["max_id"] = NSNumber(longLong: max_id)
        }

        let debug = false
        if debug {
//             加载数据
            loadLocalStatuses()
            return
        }
        
        TZWNetWorkTool.NetInstance.GET(urlString, parameters: parameters, progress: nil, success: { (task, responseObject) -> Void in
//            HMPrint("获取微博数据成功了: \(responseObject)")
            
            if let dict = responseObject as? [String: AnyObject],let statusesDict = dict["statuses"] as?[[String: AnyObject]]{
                var statusModels: [TZWStatus] = []
                
//          遍历每一个字典
            for dict in statusesDict{
//                字典转模型
                let status = TZWStatus(dict: dict)
                
                statusModels .append(status)
            }
                // 缓存图片
                self.cacheWebImage(statusModels,loadStatusCallback: loadStatusCallback)

            }
            }) { (task, error) -> Void in
                loadStatusCallback(statuses: nil, error: error)
//                HMPrint("获取微博数据失败了: \(error)")
        }
    }
    
    
//    缓存微博图片
    private func cacheWebImage (statuses: [TZWStatus],loadStatusCallback: (statuses: [TZWStatus]?, error: NSError?) -> ()){
//       判断每个模型,看看是不是有图片要下载
        
//      创建任务组
        let group = dispatch_group_create()
//       判断每个模型,看看是不是有图片要下载
        
        for status in statuses {
            var downloadURLs: [NSURL]?
            
            downloadURLs = status.storePicutreURLs
            
            // 如果原创没有图片要下载,看被转发微博是不是有图片要下载
                if downloadURLs == nil{
                    downloadURLs = status.retweeted_status?.storePicutreURLs
            }
            // 看看是否有图片要下载
            if let urls = downloadURLs{
                
                if urls.count == 1{
                    let url = urls.first!
                    dispatch_group_enter(group)
                    SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed: { (image, error, _, _, _) -> Void in
//                      异步完成之后回调这个闭包
                        dispatch_group_leave(group)
                        if error != nil{
                            HMPrint("下载图片失败: \(url)")
                            return
                        }
                    })
                }
            }
            
        }
//       监听所有的微博下载图片完成
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            // SD下载所有图片完成,回调控制器,控制器会拿到数据,然后刷新界面
            loadStatusCallback(statuses: statuses, error: nil)
            
            
        }
    }

}
